/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.services;
/*
 * @author Brandon Wong
 */
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.apps.datastore.dao.GeoLocationObject;
import com.apps.utils.WrapperUtils;

public class GoogleLocationService {
	
	public GoogleLocationService(){
		
	}
	
	public String[] getLatLong(String address){
		String[] out = new String[2];
		out[0] = "";
		out[1] = "";
		try {
			 out = parseLatLong(getGeocodeXml(address));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out;
		
	}

	private String getGeocodeXml(String address) throws MalformedURLException,
			IOException {

		String q_address = address.replaceAll(" ", "\\+");

		String url = "http://maps.googleapis.com/maps/api/geocode/xml?address="
				+ q_address + "&sensor=false";


		BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
				url).openStream()));
		
		StringBuilder strXml=new StringBuilder();
		try{
			String line = br.readLine();
			
			while (line != null) {
				line = br.readLine();
				strXml.append(line);
			}
			return strXml.toString();
		}
		finally{
			br.close();
		}
		
	}
	
	private String[] parseLatLong(String strXml){
		
		String latlngxml = WrapperUtils.stringInBwtn("<location>", "</location>", strXml);
		String[] latlng = new String[2];
		latlng[0] = WrapperUtils.stringInBwtn("<lat>", "</lat>", latlngxml);	
		latlng[1] = WrapperUtils.stringInBwtn("<lng>", "</lng>", latlngxml);
		return latlng;
		
		
	}
}
